from flask import Blueprint, render_template, redirect, url_for, request, session, flash
from db_utils import DbUtils

#蓝图定义
home_bp = Blueprint('home', __name__)  

@home_bp.route('/')
def home():
    return redirect(url_for('home.blog'))


@home_bp.route('/blog')
def blog():
    db = DbUtils()  
    try:
        users = db.query("SELECT * FROM users")
        latest_articles = db.query("SELECT * FROM articles ORDER BY create_date DESC LIMIT 5")
        popular_articles = db.query("SELECT * FROM articles ORDER BY `reads` DESC LIMIT 5")
        return render_template('home/index.html',  # 使用相对路径
                    users=users, 
                    latest_articles=latest_articles, 
                    popular_articles=popular_articles)
    finally:
        db.close()

@home_bp.route('/article')
def article_detail():
    return render_template('home/article-detail.html')

@home_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if not username or not password:
            flash("用户名和密码不能为空", 'danger')
            return redirect(url_for('home.login'))

        db = DbUtils()
        try:
            user = db.query(
                "SELECT * FROM users WHERE username = %s AND password = %s",
                (username, password)
            )

            if user:
                session['user_id'] = user[0]['id']
                session['user_nickname'] = user[0]['nickname']
                return redirect(url_for('admin.admin_articles'))
            else:
                flash("用户名或密码错误", 'danger')
                return redirect(url_for('home.login'))

        except Exception as e:
            # 打印错误信息到控制台
            print(f"【登录错误】{e}")
            flash("系统错误，请稍后再试", 'danger')
            return render_template('shared/500.html'), 500
        finally:
            db.close()

    return render_template('home/login.html')

@home_bp.route('/blog/<int:user_id>')
def blog_user(user_id):
    db = DbUtils()
    try:
        users = db.query("SELECT * FROM users WHERE id = %s", (user_id,))
        if not users:
            return render_template('shared/404.html'), 404
        user = users[0]
        
        categories = db.query("""
            SELECT DISTINCT c.id, c.name 
            FROM categories c
            JOIN articles a ON c.id = a.category_id
            WHERE a.author_id = %s
        """, (user_id,)) or []
        
        articles = db.query("""
            SELECT a.*, c.name AS category_name 
            FROM articles a
            LEFT JOIN categories c ON a.category_id = c.id
            WHERE a.author_id = %s
            ORDER BY a.create_date DESC
        """, (user_id,)) or []
        
        hot_articles = db.query("""
            SELECT id, title, content, `reads`
            FROM articles 
            WHERE author_id = %s 
            ORDER BY `reads` DESC 
            LIMIT 5
        """, (user_id,)) or []
        
        return render_template('home/blog_user.html',
                            user=user,
                            categories=categories,
                            articles=articles,
                            hot_articles=hot_articles)
    except Exception as e:
        print(f"Error in blog_user route: {str(e)}")
        return render_template('shared/500.html'), 500
    finally:
        db.close()